/******************************************************************
*
*	CyberHTTP for Java
*
*	Copyright (C) Satoshi Konno 2002-2003
*
*	File: HTTPResponse.java
*
*	Revision;
*
*	11/18/02
*		- first revision.
*	10/22/03
*		- Changed to initialize a content length header.
*	
******************************************************************/

package org.cybergarage.http;

import java.io.*;

public class HTTPResponse extends HTTPPacket
{
	////////////////////////////////////////////////
	//	Constructor
	////////////////////////////////////////////////
	
	public HTTPResponse()
	{
		setContentType(HTML.CONTENT_TYPE);
		setServer(HTTPServer.getName());
		setContent("");
	}

	public HTTPResponse(HTTPResponse httpRes)
	{
		set(httpRes);

    //
    // HTTPPacket set routine doesn't set status code properly if response
    // code was set manually (as opposed to arriving on the first line
    // of the HTTP response.  Override it here for now as quick fix.
    // TODO: Better fix would be to remove use of 'firstLine' field from 
    // HTTP package (except as a temporary when reading a packet) and
    // consistently use an HTTPStatus object within the HTTPResponse object
    // for all get/set access to status.
    // 
    setStatusCode( httpRes.getStatusCode() );  // OJN
	}

	public HTTPResponse(InputStream in)
	{
		super(in);
	}

	public HTTPResponse(HTTPSocket httpSock)
	{
		this(httpSock.getInputStream());
	}

	////////////////////////////////////////////////
	//	Status Line
	////////////////////////////////////////////////

	private int statusCode = 0;
	
	public void setStatusCode(int code)
	{
		statusCode = code;
	}

	public int getStatusCode()
	{
		if (statusCode != 0)
			return statusCode;

    String firstLine =  getFirstLine();
		HTTPStatus httpStatus = new HTTPStatus(getFirstLine());
    statusCode = httpStatus.getStatusCode();  // OJN mod

		return statusCode;
	}

	public String getStatusLineString()
	{
		return "HTTP/" + getVersion() + " " + getStatusCode() + " " +
            HTTPStatus.code2String(statusCode) + HTTP.CRLF;
	}
	
	////////////////////////////////////////////////
	//	getHeader
	////////////////////////////////////////////////
	
	public String getHeader()
	{
		StringBuffer str = new StringBuffer();
	
		str.append(getStatusLineString());
		str.append(getHeaderString());
		
		return str.toString();
	}

	////////////////////////////////////////////////
	//	toString
	////////////////////////////////////////////////
	
	public String toString()
	{
		StringBuffer str = new StringBuffer();

		str.append( getStatusLineString() );
		str.append( getHeaderString() );
		str.append( HTTP.CRLF );
		str.append( getContentString() );
		
		return str.toString();
	}

	public void print()
	{
		System.out.println(toString());
	}
}
